package io.dshubs.archives.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.dshubs.archives.dao.ArchiveBaseRuleMapper;
import io.dshubs.archives.dao.ArchiveWarehouseLocationMapper;
import io.dshubs.archives.dao.ArchiveWarehouseZoneMapper;
import io.dshubs.archives.entity.ArchiveBaseCategory;
import io.dshubs.archives.entity.ArchiveBaseRule;
import io.dshubs.archives.entity.ArchiveWarehouseLocation;
import io.dshubs.archives.entity.ArchiveWarehouseZone;
import io.dshubs.archives.service.ArchiveWarehouseLocationService;
import io.dshubs.archives.service.ArchiveWarehouseZoneService;
import io.dshubs.commons.mybatis.enums.DelFlagEnum;
import io.dshubs.commons.mybatis.service.impl.BaseServiceImpl;
import io.dshubs.commons.security.context.TenantContext;
import io.dshubs.commons.security.user.SecurityUser;
import io.dshubs.commons.security.user.UserDetail;
import io.dshubs.commons.tools.constant.Constant;
import io.dshubs.commons.tools.enums.SuperAdminEnum;
import io.dshubs.commons.tools.exception.RenException;
import io.dshubs.commons.tools.page.PageData;
import io.dshubs.commons.tools.utils.Result;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author tan 2021/8/17
 **/
@Service
public class ArchiveWarehouseZoneServiceImpl extends BaseServiceImpl<ArchiveWarehouseZoneMapper, ArchiveWarehouseZone> implements ArchiveWarehouseZoneService {

    @Autowired
    private ArchiveWarehouseLocationMapper archiveWarehouseLocationMapper;

    @Autowired
    private ArchiveWarehouseLocationService archiveWarehouseLocationService;

    @Override
    public PageData<ArchiveWarehouseZone> page(Map<String, Object> params) {
        IPage<ArchiveWarehouseZone> page = baseDao.selectPage(
                getPage(params, Constant.CREATE_DATE, false),
                getWrapper(params)
        );

        return getPageData(page, ArchiveWarehouseZone.class);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void deleteBatch(List<Long> ids) {
        List<ArchiveWarehouseLocation> locationList = archiveWarehouseLocationMapper.selectList(
                new QueryWrapper<ArchiveWarehouseLocation>().in("zone_id", ids));
        if(CollectionUtils.isNotEmpty(locationList)) {
            throw new RenException("该库区下存在密集架,不能删除");
        }
        this.baseDao.deleteBatchIds(ids);
    }

    @Override
    public void save(ArchiveWarehouseZone archiveWarehouseZone) {
        this.baseDao.insert(archiveWarehouseZone);

        List<ArchiveWarehouseLocation> locationList = this.archiveWarehouseLocationMapper.selectBatchIds(archiveWarehouseZone.getArchiveWarehouseLocationIds());

        if(CollectionUtils.isNotEmpty(locationList)) {
            locationList.forEach(i->{
                i.setZoneId(archiveWarehouseZone.getId());
                this.archiveWarehouseLocationMapper.updateById(i);
            });

        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void update(ArchiveWarehouseZone archiveWarehouseZone) {

        List<ArchiveWarehouseLocation> locationList = this.archiveWarehouseLocationMapper.selectList(
                new QueryWrapper<ArchiveWarehouseLocation>()
                        .eq("warehouse_id", archiveWarehouseZone.getWarehouseId())
                        .eq("zone_id", archiveWarehouseZone.getId())
        );
        if(CollectionUtils.isNotEmpty(locationList)) {
            Optional<ArchiveWarehouseLocation> first = locationList.stream().filter(item -> "LOCKED".equals(item.getInoutLock())).findFirst();
            if(first.isPresent()) {
                throw new RenException("该库区存在档案，不能修改");
            }
            locationList.forEach(i->{
                i.setZoneId(null);
            });
            archiveWarehouseLocationService.updateBatchById(locationList);
        }
        this.baseDao.deleteById(archiveWarehouseZone);
        save(archiveWarehouseZone);
    }

    private QueryWrapper<ArchiveWarehouseZone> getWrapper(Map<String, Object> params){
        UserDetail user = SecurityUser.getUser();
        String warehouseId = (String)params.get("warehouseId");
        String zoneCode = (String)params.get("zoneCode");
        String zoneName = (String)params.get("zoneName");
        QueryWrapper<ArchiveWarehouseZone> wrapper = new QueryWrapper<>();
        wrapper.eq(Constant.DEL_FLAG, DelFlagEnum.NORMAL.value());
        wrapper.like(StringUtils.isNotBlank(warehouseId), "warehouse_id", warehouseId);
        wrapper.eq(StringUtils.isNotBlank(zoneCode),"zone_code",zoneCode);
        wrapper.eq(StringUtils.isNotBlank(zoneName),"zone_name",zoneName);
        if(user.getSuperAdmin() != SuperAdminEnum.YES.value()) {
            wrapper.eq("tenant_code", TenantContext.getTenantCode(user));
        }
        return wrapper;
    }
}
